package com.example.service;

import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.alibaba.ocean.rawsdk.common.SDKResult;
import com.alibaba.trade.param.AlibabaAscpTradeModelTradeInfo;
import com.alibaba.trade.param.AlibabaAscpTradeSellerViewGetListParam;
import com.alibaba.trade.param.AlibabaAscpTradeSellerViewGetListResult;
import com.example.shiti.ProductItemInfo;
import com.example.shiti.TradeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GetAllOrder {
    private final String appKey = "3751877";
    private final String appSecret = "5eJGGnlEzs";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private final String redisTokenKey = "accessToken";  // Redis 中存储 Token 的键名
    @Autowired
    private SearchService searchService;
    public void GetAllOrderSave(AlibabaAscpTradeSellerViewGetListParam param) {//从服务器获取订单
        SDKResult<AlibabaAscpTradeSellerViewGetListResult> sdkResult = new SDKResult<>();
        ApiExecutor apiExecutor = new ApiExecutor(appKey, appSecret);
        for (int i = 1; i <= 10000000; i++) {
            param.setPage(i);
            sdkResult = apiExecutor.execute(param,redisTemplate.opsForValue().get(redisTokenKey));
            AlibabaAscpTradeModelTradeInfo[] array = sdkResult.getResult().getResult();
            if (array.length == 0){
                break;
            }
            TradeInfoRepository save = new TradeInfoRepository();
            for (AlibabaAscpTradeModelTradeInfo info:array) {
                save.saveTradeInfo(TradeInfoConverter.convert(info));
            }
        }
    }
    public List<TradeInfo> GetAllTradeInfoMysql(Date startTime, Date endTime, Sort sort, String key, String value, String status) {//从数据库获取订单
        List<TradeInfo> TradeInfos = searchService.findTradeInfoBetweenCreateTimes(startTime, endTime, sort, key, value,status);
        List<String> tradeInfoIds = new ArrayList<String>();
        for (TradeInfo tradeInfo:TradeInfos){
            tradeInfoIds.add(tradeInfo.getId());
        }
        Map<String,List<ProductItemInfo>> productItemInfoList = searchService.findTradeInfosByTradeInfoIds(tradeInfoIds);
        for (TradeInfo tradeInfo:TradeInfos){
            tradeInfo.setProductItems(productItemInfoList.get(tradeInfo.getId()));
        }
        return TradeInfos;
    }


}
